//
//  SetPlanController.m
//  PosApp
//
//  Created by 刘萍 on 2018/9/8.
//  Copyright © 2018年 李英新. All rights reserved.
//

#import "SetPlanController.h"
#import "ChooseAddressController.h"
#import "PlanNewsController.h"
#import "ChooseTimeController.h"
#import "PlanNewsClassModel.h"
#import "PlanNewsCellModel.h"
#import <CoreLocation/CoreLocation.h>

@interface SetPlanController ()<ChooseAddressControllerDelegate,CLLocationManagerDelegate>
@property (nonatomic, strong) CLLocationManager *locationManager;
@property (weak, nonatomic) IBOutlet UIImageView *YHImage;
@property (weak, nonatomic) IBOutlet UILabel *YHNameLabel;
@property (weak, nonatomic) IBOutlet UILabel *YHCardNumb;
@property (weak, nonatomic) IBOutlet UILabel *Time01;
@property (weak, nonatomic) IBOutlet UILabel *Time02;
@property (weak, nonatomic) IBOutlet UILabel *ShengLabel;

@property (weak, nonatomic) IBOutlet UILabel *ShiLabel;

@property (weak, nonatomic) IBOutlet UITextField *PriceText;
@property (weak, nonatomic) IBOutlet UITextField *NumbText;
@property (weak, nonatomic) IBOutlet UILabel *BeginTime;
@property (weak, nonatomic) IBOutlet UILabel *EndTime;
@property (strong, nonatomic) NSString * begin;
@property (strong, nonatomic) NSString * end;

@property (strong, nonatomic) NSString * OrderNumb;
@property (strong, nonatomic) NSString * AllPrice;
@property (strong, nonatomic) NSString * AllNumb;
@property (strong, nonatomic) NSString * AllTime;
@property (strong, nonatomic) NSMutableArray * ClassArr;
@property (strong, nonatomic) NSMutableArray * CellArr;
@property (strong, nonatomic) MBProgressHUD * hud;


@property (nonatomic ,copy) NSString * gip;//公网ip
@end

@implementation SetPlanController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.navigationItem.title = @"制定计划";
    
    self.begin = @"";
    self.end = @"";
    self.PriceText.keyboardType = UIKeyboardTypeNumberPad;
    self.NumbText.keyboardType = UIKeyboardTypeNumberPad;
    [self.YHImage sd_setImageWithURL:[NSURL URLWithString:self.headModel.card_icon] placeholderImage:[UIImage imageNamed:@"MainZWImage"]];
    self.YHNameLabel.text = [NSString stringWithFormat:@"%@",self.headModel.card_name];
    self.YHCardNumb.text = [NSString stringWithFormat:@"%@",self.headModel.card_number];
    self.Time01.text = [NSString stringWithFormat:@"账单日（%@号）",self.headModel.card_zd];
    self.Time02.text = [NSString stringWithFormat:@"还款日（%@号）",self.headModel.card_hk];
    
    [self startLocation];
    dispatch_async(dispatch_get_main_queue(), ^{
        self.gip = [self urlRequestOperation];//[self deviceWANIPAddress];
    });
}

- (IBAction)ClickOnBtnToChooseAddress:(id)sender {
    ChooseAddressController * chooseC = [[ChooseAddressController alloc] init];
    chooseC.delegate = self;
    chooseC.modalPresentationStyle = UIModalPresentationOverFullScreen;
    [self presentViewController:chooseC animated:YES completion:nil];
}

- (void)ClickOnBtnToUploadChooseAddressShengString:(NSString *)sheng andShi:(NSString *)Shi {
    self.ShengLabel.text = [NSString stringWithFormat:@"%@",sheng];
    self.ShiLabel.text = [NSString stringWithFormat:@"%@",Shi];
}

- (IBAction)ClickOnBtnToChooseBeginTime:(id)sender {
    
    ChooseTimeController * chooseC = [[ChooseTimeController alloc] init];
    chooseC.timeBlock = ^(NSString *timeStr) {
        self.begin = [NSString stringWithFormat:@"%@",timeStr];
        self.BeginTime.text = self.begin;
    };
    chooseC.modalPresentationStyle = UIModalPresentationOverFullScreen;
    [self presentViewController:chooseC animated:YES completion:nil];
    
}
- (IBAction)ClickOnBtnToChooseEndTime:(id)sender {
    ChooseTimeController * chooseC = [[ChooseTimeController alloc] init];
    chooseC.timeBlock = ^(NSString *timeStr) {
        self.end = [NSString stringWithFormat:@"%@",timeStr];
        self.EndTime.text = self.end;
    };
    
    chooseC.modalPresentationStyle = UIModalPresentationOverFullScreen;
    [self presentViewController:chooseC animated:YES completion:nil];
    
    
}
- (IBAction)ClickOnBtnToTureThePlan:(id)sender {
    if (self.ShiLabel.text.length == 0) {
        [MBProgressHUD showAlertViewWithText:@"请选择地区"];
        return;
    }
    if (self.PriceText.text.length == 0) {
        [MBProgressHUD showAlertViewWithText:@"请填写账单金额"];
        return;
    }
    
    if ([self.NumbText.text floatValue] < 1) {
        [MBProgressHUD showAlertViewWithText:@"请填写消费次数"];
        return;
    }
    
    if (self.begin.length == 0) {
        [MBProgressHUD showAlertViewWithText:@"请选择开始时间"];
        return;
    }
    
    if (self.end.length == 0) {
        [MBProgressHUD showAlertViewWithText:@"请选择结束时间"];
        return;
    }
    
    NSMutableDictionary * dic = [[NSMutableDictionary alloc] init];
    [dic setObject:KUserID forKey:@"card_member"];
    [dic setObject:self.headModel.card_id forKey:@"card_id"];
    [dic setObject:self.PriceText.text forKey:@"money"];
    [dic setObject:self.NumbText.text forKey:@"count"];
    [dic setObject:self.begin forKey:@"start"];
    [dic setObject:self.end forKey:@"end"];
    [dic setObject:self.ShengLabel.text forKey:@"province"];
    [dic setObject:self.ShiLabel.text forKey:@"city"];
    [dic setObject:self.gip forKey:@"ip"];
    
    self.hud = [MainObjectWay CreateHUDView:self.view];
    
    
    [MainObjectWay PostWithMethod:@"plan" andAction:@"Creditcard" andAddParam:YES parameters:dic success:^(id responseObject) {
        NSLog(@"请求的信息 = %@",responseObject);
        NSLog(@"xiaoxi = %@",responseObject[@"msg"]);
        if ([MainObjectWay IsSucceedWithCode:responseObject[@"code"]]) {
            NSMutableDictionary * dic = responseObject[@"data"];
            [self.hud hideAnimated:YES];
            PlanNewsController * PlanC = [[PlanNewsController alloc] init];
            PlanC.ShowBot = YES;
            PlanC.DataDic = dic;
            PlanC.CardModel = self.headModel;
            [self.navigationController pushViewController:PlanC animated:YES];
        }else{
            [self.hud hideAnimated:YES];
            [MBProgressHUD showAlertViewWithText:responseObject[@"msg"]];
        }
    } failure:^(NSError *error) {
        [self.hud hideAnimated:YES];
        NSLog(@"错误信息 = %@",error);
    }];
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}


- (NSMutableArray *)ClassArr {
    if (!_ClassArr) {
        _ClassArr = [NSMutableArray array];
    }
    return _ClassArr;
}

- (NSMutableArray *)CellArr {
    if (!_CellArr) {
        _CellArr = [NSMutableArray array];
    }
    return _CellArr;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark - 定位
- (void)startLocation
{
    if ([CLLocationManager locationServicesEnabled])
    {
        XHQHUDSHOW(self.view);
        _locationManager = [[CLLocationManager alloc]init];
        _locationManager.delegate = self;
        [_locationManager requestAlwaysAuthorization];
        [_locationManager requestWhenInUseAuthorization];
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        _locationManager.distanceFilter = 5.0;
        [_locationManager startUpdatingLocation];
    }
    else
    {
        XHQHUDTEXT(@"定位失败，定位功能不可使用");
    }
}

#pragma mark - CLLocationManagerDelegate
#pragma mark - 定位失败
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    XHQHUDHIDE(self.view);
    JWALERT_TWO_ACTION_SHOW(@"请您先开启定位权限\n才能完成授权",
                            nil,
                            @"开启",
                            @"取消",
                            [self openSetting],
                            nil);
}
#pragma mark - 打开设置
- (void)openSetting
{
    XHQHUDHIDE(self.view);
    NSURL *settingURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
    [[UIApplication sharedApplication]openURL:settingURL];
}

#pragma mark - 定位成功
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    XHQHUDHIDE(self.view);
    [_locationManager stopUpdatingLocation];
    
    CLLocation *currentLocation = [locations lastObject];
    //    self.latitude = currentLocation.coordinate.latitude;
    //    self.longitude = currentLocation.coordinate.longitude;
    //
    //    XHQ_Log(@"latitude:%f - latitude:%f", self.latitude, self.longitude);
    
    // 获取当前所在的城市名
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    //根据经纬度反向地理编译出地址信息
    [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *array, NSError *error){
        if (array.count > 0){
            CLPlacemark *placemark = [array objectAtIndex:0];
            //将获得的所有信息显示到label上
            NSLog(@"%@",placemark.name);
            
            NSString * previence = placemark.administrativeArea;
            //获取城市
            NSString *city = placemark.locality;
            if (!city) {
                //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
                city = placemark.administrativeArea;
                //                self.cityName = city;
            }else if (error == nil && [array count] == 0){
                NSLog(@"No results were returned.");
            }else if (error != nil){
                NSLog(@"An error occurred = %@", error);
            }
            
//            self.provinceName = previence;
//            self.cityName = city;
//            //            DYInputCellItem *item = self.dataArray[4];
//            //            item.inputString = self.provinceName;
//            //            item = self.dataArray[5];
//            //            item.inputString = self.cityName;
//            //            [self.tableView reloadData];
//
//            [self areaReqCCCCCCC:@""];
            
            self.ShengLabel.text = previence;
            self.ShiLabel.text = city;
        }
    }];
    
}



-(NSString *)deviceWANIPAddress
{
    NSURL *ipURL = [NSURL URLWithString:@"http://ip.taobao.com/service/getIpInfo.php?ip=myip"];
    NSData *data = [NSData dataWithContentsOfURL:ipURL];
    NSDictionary *ipDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]; 
    NSString *ipStr = nil;
    if (ipDic && [ipDic[@"code"] integerValue] == 0) { //获取成功
        ipStr = ipDic[@"data"][@"ip"];
    }
    return (ipStr ? ipStr : @"");
}
- (NSString *)urlRequestOperation{NSError *error;NSURL *ipURL = [NSURL URLWithString:@"http://ifconfig.me/ip"];return   [NSString stringWithContentsOfURL:ipURL encoding:NSUTF8StringEncoding error:&error];}

@end
